/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.nh.glory.admin.modular.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nh.glory.core.R;
import com.nh.glory.core.node.INode;
import com.nh.glory.core.util.Func;
import com.nh.glory.data.model.Dept;
import com.nh.glory.data.vo.DeptVO;
import com.nh.glory.ware.service.system.DeptService;
import com.nh.glory.ware.support.Condition;
import com.nh.glory.ware.wrapper.DeptWrapper;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 控制器
 *
 */
@RestController
@AllArgsConstructor
@RequestMapping("/dept")
public class DeptController {

	private DeptService deptService;

	/**
	 * 详情
	 */
	@GetMapping("{id}")
	public R<DeptVO> detail(@PathVariable Integer id) {
		Dept detail = deptService.getById(id);
		DeptWrapper deptWrapper = new DeptWrapper(deptService);
		return R.ok(deptWrapper.entityVO(detail));
	}

	/**
	 * 列表
	 */
	@GetMapping
	public R<List<INode>> list(@RequestParam Map<String, Object> dept) {
		QueryWrapper<Dept> queryWrapper = Condition.getQueryWrapper(dept, Dept.class);
		List<Dept> list = deptService.list(queryWrapper);
		DeptWrapper deptWrapper = new DeptWrapper(deptService);
		return R.ok(deptWrapper.listNodeVO(list));
	}

	/**
	 * 获取部门树形结构
	 *
	 * @return
	 */
	@GetMapping("/tree")
	public R<List<DeptVO>> tree() {
		List<DeptVO> tree = deptService.tree();
		return R.ok(tree);
	}

	/**
	 * 新增或修改
	 */
	@PostMapping
	public R submit(@Valid @RequestBody Dept dept) {
		if(dept.getId() == null) {
			if(dept.getParentId() == null) dept.setParentId(0L);
			if(dept.getDeleted() == null) dept.setDeleted(0);
		}
		return R.status(deptService.saveOrUpdate(dept));
	}

	/**
	 * 删除
	 */
	@DeleteMapping
	public R remove(@RequestParam String ids) {
		return R.status(deptService.removeByIds(Func.toIntList(ids)));
	}


}
